#include "core/stl/Thread.h"

using namespace Stl;

bool Thread::End()
{
    return m_State == _state_end_;
};


bool Thread::Waiting()
{
    return m_State == _state_waiting_;
};

bool Thread::Working()
{
    return m_State == _state_working_;
};

bool Thread::Joinable()
{
    return m_Inst->joinable();
};

void Thread::Execute(Thread* inst)
{

    if (inst)
    {
        inst->m_State = _state_working_;
        inst->Run();
        inst->m_State = _state_end_;
    }
};

void Thread::TryJoin()
{
    if (Joinable())
    {
        Join();
    }
};

void Thread::Swap(std::shared_ptr<Thread> other)
{
    m_Inst->swap(*other->m_Inst);
}

std::thread::native_handle_type Thread::NativeHandle()
{
    return m_Inst->native_handle();
}

std::thread::id Thread::GetId()
{
    return m_Inst->get_id();
};

void Thread::Detach()
{
    m_Inst->detach();
}

void Thread::Start()
{

    if (m_State != _state_waiting_)
    {
        ztclog::warn("current state is not waiting");
    }
    else
    {
        m_Inst = std::make_shared<std::thread>(Execute, this);
        m_State = Thread::State::_state_working_;
    }
};

void Thread::Join()
{
    m_Inst->join();
};

Thread::~Thread()
{
    TryJoin();
};